package priv.wjh.study.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class NioClient {

    private static Selector selector;
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    public static void main(String[] args) throws IOException {
        selector = Selector.open();

        for (int i = 0; i < 5; i++) {
            Executors.newSingleThreadExecutor().submit(() -> {
                try {
                    runClient();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }


        while (true){
            int select = selector.select(1000);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keys = selectionKeys.iterator();
            while (keys.hasNext()){
                SelectionKey key = keys.next();
                keys.remove();
                final int i = (int) key.attachment();
                if (key.isConnectable()){
                    SelectableChannel channel = key.channel();
                    if (channel instanceof SocketChannel curSocketChannel){
                        if (curSocketChannel.isConnectionPending()){
                            curSocketChannel.finishConnect();
                        }
                        curSocketChannel.configureBlocking(false);
                        curSocketChannel.write(ByteBuffer.wrap((i + " : hello").getBytes()));
                        curSocketChannel.register(selector, SelectionKey.OP_READ, i);
                    }
                } else if (key.isReadable()) {
                    SelectableChannel channel = key.channel();
                    if (channel instanceof SocketChannel curSocketChannel){
                        ByteBuffer buffer = ByteBuffer.allocate(128);
                        curSocketChannel.read(buffer);
                        byte[] data = buffer.array();
                        String msg = new String(data).trim();
                        System.out.println(msg);
                    }
                }
            }
            if (select == 0){
                System.out.println("time out");
            }
        }
    }

    public static void runClient() throws IOException {

        final int i = ATOMIC_INTEGER.incrementAndGet();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 10001));

        socketChannel.register(selector, SelectionKey.OP_CONNECT, i);

    }
}
